//
//  ZYDeviceDetailVC.m
//  YiLin
//
//  Created by Zyark on 2018/12/17.
//  Copyright © 2018 Zyark. All rights reserved.
//

#import "ZYDeviceDetailVC.h"
#import "ZYDeviceSwitchView.h"
#import "ZYDevice.h"
#import "ZYCurve.h"
#import "ZYImageUtils.h"
#import "ZYDeviceItemView.h"
#import "ZYDeviceCommonItemView.h"
#import "ZYDeviceVSItemView.h"
#import "iCarousel.h"
#import "ZYWorkModeSelectView.h"
#import "ZYModeTypeModel.h"
#import "ZYCircleHanderView.h"
#import "ZYQuickSetupVC.h"
#import "ZYVSQuickSetupVC.h"
#import "ZYDeviceModifyVC.h"
#import "ZYDeviceAddVC.h"
#import "ZYDevicePolicyVC.h"
#import "ZYHistoricalDataVC.h"
#import "ZYDeviceViewModel.h"
#import "ZYSocketMessageUtils.h"
#import "ZYQuickSetupViewModel.h"
#import "ZYCurveViewModel.h"
#import "RHSocketService.h"
#import "UIButton+ImageTitleSpacing.h"
#import "DeviceCommunicate.pbobjc.h"
#import "KxMenu.h"
#import "EBDropdownListView.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "NSTimer+SGLUnRetain.h"


#define CENTER_VIEW_WIDTH ZYSCREEN_W
#define CENTER_VIEW_TOP self.view.frame.size.height / 3

@interface ZYDeviceDetailVC ()<ZYDeviceSwitchViewDelegate,ZYDeviceItemViewDelegate,ZYWorkModeSelectViewDelegate>
@property(nonatomic,strong) UIImageView *bgImageView;

@property(nonatomic,strong) UIView *bgView;

/**
 设备开关View
 */
@property(nonatomic,strong) ZYDeviceSwitchView *deviceSwitchView;

/**
 设备类型
 */
@property(nonatomic,assign) ZYDeviceType deviceType;

@property(nonatomic,strong) ZYDeviceItemView *deviceItemView;


/**
 该住宅下的所有设备
 */
@property(nonatomic,strong) NSArray *deviceArray;


@property(nonatomic,strong) ZYWorkModeSelectView *workModeSelectView;

/**
 右侧空调菜单组
 */
@property(nonatomic,strong) NSArray *rightACMenuItemArray;


/**
 右侧地暖菜单组
 */
@property(nonatomic,strong) NSArray *rightRFHMenuItemArray;

/**
 右侧新风系统菜单组
 */
@property(nonatomic,strong) NSArray *rightVSMenuItemArray;

/**
 左侧菜单组
 */
@property(nonatomic,strong) NSArray *leftMenuItemArray;

/**
 是否显示右边菜单
 */
@property(nonatomic,assign) BOOL isShowRightMenu;

/**
 设备ViewModel
 */
@property(nonatomic,strong) ZYDeviceViewModel *deviceViewModel;

/**
 获取默认值
 */
@property(nonatomic,strong) ZYQuickSetupViewModel *quickSetupViewModel;

/**
 新风模式默认值
 */
@property(nonatomic,strong) NSArray *vsDefaultValueArray;

/**
 空调地暖模式默认值
 */
@property(nonatomic,strong) NSArray *defaultValueArray;

/**
 获取曲线值
 */
@property(nonatomic,strong) ZYCurveViewModel *viewModel;

/**当前曲线值*/
@property(nonatomic,strong) NSArray *currentArray;

/**定时器*/
@property(nonatomic, strong) NSTimer *timer;

@end

@implementation ZYDeviceDetailVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupRightButton];
    [self setupRightMenuItem];
    if(!NULLString(_currentDevice.mac)){
        self.viewModel.macAddress = _currentDevice.mac;
        [self.viewModel.getCustomCurveCommand execute:nil];//获取自定义曲线
    }
//    [self.deviceViewModel.deviceListCommand execute:nil];//获取该住宅设备列表
    self.fd_interactivePopDisabled = YES;
    //    if(_currentDevice.type != ZYDeviceTypeVentilationSystem){
    
    //    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.fd_interactivePopDisabled = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    // 务必在当前线程调用invalidate方法，使得Runloop释放对timer的强引用(具体请参阅官方文档)
    [self.timer invalidate];
}

#pragma mark - init
-(void)setup{
    _deviceType = _currentDevice.type;
    [self bindView];
    [self setupView];
    [self setupData];
    [self setupTimer];
}

#pragma mark - 初始化定时器
-(void)setupTimer{
    @weakify(self)
    self.timer = [NSTimer sgl_scheduledTimerWithTimeInterval:60 repeats:YES block:^(NSTimer *timer) {
        @strongify(self)
        //更新温度
        if(!self.currentDevice.isTest && self.currentDevice.modeType && (self.currentDevice.type == ZYDeviceTypeAirConditioning || self.currentDevice.type == ZYDeviceTypeRadiantFloorHeating)){
            if(self.currentDevice.modeType == ZYDeviceModeCustom){
                //获取当前时间更新温度
                [self setupCustomModelTemplate];
            }
        }
    }];
}

//-(void)setupCustomModelTemplate{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"HH"];
//    NSDate *datenow = [NSDate date];
//    NSString *currentTimeString = [formatter stringFromDate:datenow];
//    NSInteger currentHour = [currentTimeString integerValue];
//    if(self.currentArray && [self.currentArray count] > currentHour){
//        NSString *value = [self.currentArray objectAtIndex:currentHour];
//        self.currentDevice.temperature = value;
//        self.deviceItemView.device = self.currentDevice;
//    }
//}

-(void)setupCustomModelTemplate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    NSInteger currentHour = [currentTimeString integerValue];
    if(currentHour == 0){
        NSString *value = [self.currentArray lastObject];
        self.currentDevice.temperature = value;
        self.deviceItemView.device = self.currentDevice;
    }else{
        if(self.currentArray && [self.currentArray count] >(currentHour - 1)){
            NSString *value = [self.currentArray objectAtIndex:currentHour - 1];
            self.currentDevice.temperature = value;
            self.deviceItemView.device = self.currentDevice;
        }
    }
}

-(void)setupView{
    //    _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H * 0.63)];
    //    [_bgImageView setImage:[UIImage imageNamed:@"ic_home_main_device_bg_ac"]];
    //    [self.view addSubview:_bgImageView];
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H * 0.63 - 35)];
    [_bgView.layer addSublayer:[ZYUtils setGradualChangingColor:_bgView fromHexColorStr:kMainColorStartColorHexString toHexColorStr:kMainColorEndColorHexString locations:@[@0.3, @1.0]]];
    [self.view addSubview:_bgView];
    _deviceSwitchView = [[ZYDeviceSwitchView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W - 30, DEVICE_SWITCH_VIEW_COMMON_HEIGHT)];
    _deviceSwitchView.delegate = self;
    [self.view addSubview:_deviceSwitchView];
    _deviceSwitchView.centerX = self.view.centerX;
    _deviceSwitchView.top = _bgView.bottom + 10;
    
    ZYDeviceItemView *deviceItemView;
    CGFloat height = _bgView.height - 10 - SafeAreaTopHeight;
    if(_currentDevice.type == ZYDeviceTypeVentilationSystem){
        deviceItemView = [[ZYDeviceVSItemView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W,  height)];
    }else{
        deviceItemView = [[ZYDeviceCommonItemView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W,  height)];
    }
    deviceItemView.device = _currentDevice;
    deviceItemView.delegate = self;
    _deviceItemView = deviceItemView;
    [_bgView addSubview:deviceItemView];
    deviceItemView.bottom = _bgView.bottom;
    deviceItemView.centerX = _bgView.width / 2;
    
    [self setupWorkModeSelectView];
}

//绑定view
-(void)bindView{
    //设备socket地址 获取后重新连接socket
    @weakify(self)
    [[[self.deviceViewModel.deviceSocketCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self reconnectWithIp:x macAddress:self.deviceViewModel.mac isDisconnect:NO];//重新连接socket
    }];
    [self.deviceViewModel.deviceSocketCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    
    //获取该住宅设备列表
    [[[self.deviceViewModel.deviceListCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.deviceArray = x;
        [self setupData];
        
    }];
    [self.deviceViewModel.deviceListCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        if([[NSErrorHelper handleErrorMessage:x] isEqualToString:LOGIN_FAILURE]){
            //登录失效
            [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
        }
    }];
    //获取模式值
    [[[self.quickSetupViewModel.modeValueCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [self setupViewModelValue:x];
    }];
    //空调地暖模式默认值
    [[[self.quickSetupViewModel.modeDefaultCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        NSDictionary *dict = x;
        ZYModeTypeModel *esModel = [[ZYModeTypeModel alloc] init];
        esModel.modeType = ZYDeviceModeEnergySaving;
        esModel.value = [dict objectForKey:[NSString stringWithFormat:@"%ld",(long)ZYDeviceModeEnergySaving]];
        
        ZYModeTypeModel *comModel = [[ZYModeTypeModel alloc] init];
        comModel.modeType = ZYDeviceModeComfortable;
        comModel.value = [dict objectForKey:[NSString stringWithFormat:@"%ld",(long)ZYDeviceModeComfortable]];
        
        ZYModeTypeModel *customModel = [[ZYModeTypeModel alloc] init];
        customModel.modeType = ZYDeviceModeCustom;
        customModel.value = [dict objectForKey:[NSString stringWithFormat:@"%ld",(long)ZYDeviceModeCustom]];
        
        self.defaultValueArray = @[esModel,comModel,customModel];
        [self setupDefaultValue];
    }];
    //新风模式默认值
    [[[self.quickSetupViewModel.vsFilterCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        NSDictionary *dict = x;
        self.vsDefaultValueArray = [dict objectForKey:@"mode"];
        [self setupDefaultValue];
    }];
    [self.quickSetupViewModel.modeValueCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    
    //删除设备
    [[[self.deviceViewModel.deleteCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_DELETE_DEVICE_SUCCESS]];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    [self.deviceViewModel.deleteCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:x message:[NSErrorHelper handleErrorMessage:x] controller:self];
    }];
    
    //获取自定义曲线值
    [[self.viewModel.getCustomCurveCommand.executionSignals switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        ZYCurve *curve = x;
        NSString *value = curve.value;
        NSArray *valueArray = [value componentsSeparatedByString:@","];;
        self.currentArray = valueArray;
    }];
}

/**
 设置设备默认的温度或风速
 */
-(void)setupDefaultValue{
    NSArray *array;
    self.quickSetupViewModel.mac = _currentDevice.mac;
    if(_currentDevice.type == ZYDeviceTypeVentilationSystem){
        array = self.vsDefaultValueArray;
        if(!array || [array count] == 0){
            [self.quickSetupViewModel.vsFilterCommand execute:nil];
            return;
        }
    }else{
        array = self.defaultValueArray;
        if(!array || [array count] == 0){
            [self.quickSetupViewModel.modeDefaultCommand execute:nil];
            return;
        }
    }
    //获取模式值
    [self.quickSetupViewModel.modeValueCommand execute:[NSNumber numberWithUnsignedInteger:_currentDevice.serverDeviceType]];
}

//初始化视图
-(void)setupViewModelValue:(NSArray *)modelArray{
    for (ZYModeTypeModel *model in modelArray) {
        if(model.modeType != self.currentDevice.modeType){
            continue;
        }
        [self setupSocketWithModel:model];
        return;
    }
    if(_currentDevice.type == ZYDeviceTypeVentilationSystem){
        modelArray = self.vsDefaultValueArray;
    }else{
        modelArray = self.defaultValueArray;
    }
    for (ZYModeTypeModel *model in modelArray) {
        if(model.modeType != self.currentDevice.modeType){
            continue;
        }
        [self setupSocketWithModel:model];
        return;
    }
}

-(void)setupSocketWithModel:(ZYModeTypeModel *)model{
    NSDictionary *dict;
    if(self.deviceType == ZYDeviceTypeVentilationSystem){//新风系统
        NSUInteger type ;
        if(model.modeType == ZYVSModeTypeAuto){
            type = model.autoWindSpeedType;
        }else{
            type = model.speedType;
        }
        if(_currentDevice.isNewVS){//新风风速 1-10级
            ZYWindSpeedIn100Type windSpeedIn100Type;
            switch (model.speedType) {
                case ZYWindSpeedTypeHeight:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeHeight;
                    break;
                case ZYWindSpeedTypeMiddle:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeMiddle;
                    break;
                case ZYWindSpeedTypeLow:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeLow;
                    break;
                default:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeMiddle;
                    break;
            }
            type = windSpeedIn100Type;
        }
        //改变当前风速
        if(model.modeType == ZYVSModeTypeAuto){//新风自动模式
            self.currentDevice.windSpeedType = model.autoWindSpeedType;
            //socket控制设备
            
            NSString *sleepTime = [NSString stringWithFormat:@"%@:%@/%@:%@",model.startHour,model.startMinute,model.endHour,model.endMinute];
            if(_currentDevice.isNewVS){
                dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:ZYVSModeTypeAuto],@"sleepTime":sleepTime,@"cleanTime":[NSNumber numberWithInteger:model.autoMinute],@"windSpeedIn100":[NSNumber numberWithUnsignedInteger:type]};
            }else{
                dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:ZYVSModeTypeAuto],@"sleepTime":sleepTime,@"cleanTime":[NSNumber numberWithInteger:model.autoMinute],@"windSpeed":[NSNumber numberWithUnsignedInteger:type]};
            }
        }else{
            if(model.modeType == ZYVSModeTypeMixedWind){
                if(_currentDevice.isNewVS){
                    dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:ZYVSModeTypeMixedWind],@"windSpeedIn100":[NSNumber numberWithFloat:type],@"valvaAngleInMixWind":[NSNumber numberWithInt:model.proportion]};
                }else{
                    dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:ZYVSModeTypeMixedWind],@"windSpeed":[NSNumber numberWithFloat:type],@"valvaAngleInMixWind":[NSNumber numberWithInt:model.proportion]};
                }
            }else{
                if(_currentDevice.isNewVS){
                    dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:model.modeType],@"windSpeedIn100":[NSNumber numberWithFloat:type]};
                }else{
                    dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:model.modeType],@"windSpeed":[NSNumber numberWithFloat:type]};
                }
            }
            self.currentDevice.windSpeedType = model.speedType;
        }
        self.deviceSwitchView.device = self.currentDevice;
    }else{//改变当前设置温度
        self.currentDevice.temperature = model.value;
        self.deviceItemView.device = self.currentDevice;
        if(_currentDevice.modeType == ZYDeviceModeCustom){//自定义模式不需要传模式
            dict = @{@"lockStatus":@0,@"powerStatus":@1,@"setTemperatureC2":model.value};
        }else{
            dict = @{@"lockStatus":@0,@"pannelModel":[NSNumber numberWithUnsignedInteger:_currentDevice.modeType],@"powerStatus":@1,@"setTemperatureC2":model.value};
        }
    }
    if(_currentDevice.isOpen){
        [ZYSocketMessageUtils setDeviceWithMac:_currentDevice.mac andParams:dict];
    }
}

-(void)setupData{
    [self setupCurrentDevice];
}

-(void)setupWorkModeSelectView{
    _workModeSelectView = [[ZYWorkModeSelectView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W, ZYSCREEN_H)];
    _workModeSelectView.delegate = self;
//    [self.view addSubview:_workModeSelectView];
}



//初始化右侧导航栏
-(void)setupRightButton{
    UIButton *button = [[UIButton alloc] init];
    button.frame = CGRectMake(0, 0, 40, 25);
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_HOME_DEVICE_EDIT_BTN_TITLE] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:16]];
    self.navigationItem.rightBarButtonItem = barButtonItem;
    [button addTarget:self action:@selector(showRightMenu:) forControlEvents:UIControlEventTouchUpInside];
    
    //    [barButtonItem setTarget:self];
    //    barButtonItem.action = @selector(popController);
    
}


/**
 初始化标题
 */
-(void)changeLanguage{
    [super changeLanguage];
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    [_deviceSwitchView setupTitle];
    
    [_workModeSelectView setupTitle];
    
    //更新设备详细信息视图
    _deviceItemView.device = _currentDevice;
}

-(ZYDevice *)setupDefaultDevice:(NSUInteger )deviceType{
    ZYDevice *device = [[ZYDevice alloc] init];
    device.type = deviceType;
    device.name = @"-";
    device.windSpeedType = ZYWindSpeedTypeMiddle;
    device.modeType = ZYDeviceModeCustom;
    device.temperature = @"10";
    device.pmExponent = @"-";
    device.pmQuality = @"-";
    device.tvoc = @"-";
    device.humidity = @"0";
    device.roomTemperature = @"-";
    device.isTest = YES;
    device.isLock = YES;
    device.isOpen = NO;
    return device;
}

-(void)setupCurrentDevice{
    ZYDevice *device = _currentDevice;
    if(device.isTest){
        if([[RHSocketService sharedInstance] isRunning]){
            [[RHSocketService sharedInstance] stopService];
        }
        return;
    }
    if([[RHSocketService sharedInstance] isRunning]){
        //更新视图
        //        _deviceItemView.device = _currentDevice;
        //        _deviceSwitchView.device = _currentDevice;
        [self getDeviceData];//重新获取
        return;
    }
    if([[RHSocketService sharedInstance] isRunning]){
        [[RHSocketService sharedInstance] stopService];
    }
    
    self.deviceViewModel.mac = _currentDevice.mac;
    [self.deviceViewModel.deviceSocketCommand execute:nil];//获取设备socket地址
}


-(void)setupRightMenuItem{
    ZYChangeLanguage *language = [[ZYChangeLanguage alloc] init];
    _rightRFHMenuItemArray =
    @[
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_TEMPERATURE_CONTROL_STRATEGY]
                     image:[UIImage imageNamed:@"ic_home_edit_temperature_control"]
                    target:self
                    action:@selector(gotoTemperatureControlStrategy)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_QUICK_SETUP]
                     image:[UIImage imageNamed:@"ic_home_edit_quick_setup"]
                    target:self
                    action:@selector(gotoQuickSetup)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_EQUIPMENT_EDITING]
                     image:[UIImage imageNamed:@"ic_home_edit_equipment_editing"]
                    target:self
                    action:@selector(gotoEquipmentEditing)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_DELETE_DEVICE]
                     image:[UIImage imageNamed:@"ic_home_edit_delete"]
                    target:self
                    action:@selector(deleteDevice)],
      ];
    _rightACMenuItemArray =
    @[
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_TEMPERATURE_CONTROL_STRATEGY]
                     image:[UIImage imageNamed:@"ic_home_edit_temperature_control"]
                    target:self
                    action:@selector(gotoTemperatureControlStrategy)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_QUICK_SETUP]
                     image:[UIImage imageNamed:@"ic_home_edit_quick_setup"]
                    target:self
                    action:@selector(gotoQuickSetup)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_WORK_MODE]
                     image:[UIImage imageNamed:@"ic_home_edit_work_mode"]
                    target:self
                    action:@selector(selectWorkMode)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_EQUIPMENT_EDITING]
                     image:[UIImage imageNamed:@"ic_home_edit_equipment_editing"]
                    target:self
                    action:@selector(gotoEquipmentEditing)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_DELETE_DEVICE]
                     image:[UIImage imageNamed:@"ic_home_edit_delete"]
                    target:self
                    action:@selector(deleteDevice)],
      ];
    _rightVSMenuItemArray =
    @[
      //      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_HISTORICAL_DATA]
      //                     image:[UIImage imageNamed:@"ic_home_edit_historical_data"]
      //                    target:self
      //                    action:@selector(gotoHistoricalData)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_QUICK_SETUP]
                     image:[UIImage imageNamed:@"ic_home_edit_quick_setup"]
                    target:self
                    action:@selector(gotoQuickSetup)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_EQUIPMENT_EDITING]
                     image:[UIImage imageNamed:@"ic_home_edit_equipment_editing"]
                    target:self
                    action:@selector(gotoEquipmentEditing)],
      [KxMenuItem menuItem:[language getStringByKey:LC_HOME_EDIT_DEVICE_DELETE_DEVICE]
                     image:[UIImage imageNamed:@"ic_home_edit_delete"]
                    target:self
                    action:@selector(deleteDevice)],
      ];
}



#pragma mark - ZYDeviceItemViewDelegate
//模式改变
-(void)deviceItemView:(ZYDeviceItemView *)deviceItemView setModeType:(NSUInteger)modeType device:(ZYDevice *)device{
    if(device.isTest){
        return;
    }
    //    NSDictionary *dict;
    //    if(device.type == ZYDeviceTypeVentilationSystem){
    //        dict = @{@"windPannelModel":[NSNumber numberWithUnsignedInteger:modeType]};
    //    }else{
    //        dict = @{@"pannelModel":[NSNumber numberWithUnsignedInteger:modeType]};
    //    }
    if(device.type == ZYDeviceTypeAirConditioning || device.type == ZYDeviceTypeRadiantFloorHeating){
        if(modeType == ZYDeviceModeCustom){
            //设置自定义温度
            NSDictionary *dict = @{@"controlFlag":@5,@"curveId":@0};
            [ZYSocketMessageUtils setDeviceWithMac:device.mac andParams:dict andCmd:5];
            [self setupCustomModelTemplate];
            return;
        }
    }
    [self setupDefaultValue];//获取模式值
    //    [ZYSocketMessageUtils setDeviceWithMac:device.mac andParams:dict];
}

-(void)deviceItemView:(ZYDeviceItemView *)deviceItemView isChangeTemperature:(BOOL)isChange{
}

//温度改变
-(void)deviceItemView:(ZYDeviceItemView *)deviceItemView changeTemperature:(int)temperature device:(ZYDevice *)device{
    if(device.isTest){
        return;
    }
    //修改socket 和http的模式温度
    //设置当前模式为手动模式
    _currentDevice.modeType = ZYDeviceModeManual;
    self.deviceItemView.device = _currentDevice;
    self.quickSetupViewModel.mac = _currentDevice.mac;
    [self.quickSetupViewModel setModeValueWithDeviceType:_currentDevice.serverDeviceType andModel:_currentDevice.modeType andParams:[NSString stringWithFormat:@"%d",temperature]];
    NSDictionary *dict = @{@"lockStatus":@0,@"pannelModel":[NSNumber numberWithUnsignedInteger:_currentDevice.modeType],@"powerStatus":@1,@"setTemperatureC2":[NSNumber numberWithInt:temperature]};
    [ZYSocketMessageUtils setDeviceWithMac:_currentDevice.mac andParams:dict];
}

#pragma mark - ZYDeviceSwitchViewDelegate

//是否锁定
-(void)deviceSwitchView:(ZYDeviceSwitchView *)deviceSwitchView setDeviceLock:(BOOL)isLock device:(ZYDevice *)device switchBtn:(UISwitch *)switchBtn{
    [_deviceItemView setIsLock:isLock];
    if(device.isTest){
        return;
    }
    NSDictionary *dict = @{@"lockStatus":isLock ? @1 : @0};
    [ZYSocketMessageUtils setDeviceStatusWithMac:device.mac andParams:dict];
}

//是否开启
-(void)deviceSwitchView:(ZYDeviceSwitchView *)deviceSwitchView setDeviceOpen:(BOOL)isOpen device:(ZYDevice *)device switchBtn:(UISwitch *)switchBtn{
    _currentDevice.isOpen = isOpen;
    [_deviceItemView setIsOpen:isOpen];
    if(device.isTest){
        return;
    }
    NSDictionary *dict = @{@"powerStatus":isOpen ? @1 : @0};
    [ZYSocketMessageUtils setDeviceStatusWithMac:device.mac andParams:dict];
}

//选择风速
-(void)deviceSwitchView:(ZYDeviceSwitchView *)deviceSwitchView setWindSpeedType:(ZYWindSpeedType)type device:(ZYDevice *)device button:(UIButton *)button{
    if(device.isTest){
        return;
    }
    NSDictionary *dict;
    if(device.type == ZYDeviceTypeVentilationSystem){
        //改为手动模式
        _currentDevice.vsModeType = ZYVSModeTypManual;
        _deviceItemView.device = _currentDevice;
        if(device.isNewVS){
            ZYWindSpeedIn100Type windSpeedIn100Type;
            switch (type) {
                case ZYWindSpeedTypeHeight:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeHeight;
                    break;
                case ZYWindSpeedTypeMiddle:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeMiddle;
                    break;
                case ZYWindSpeedTypeLow:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeLow;
                    break;
                default:
                    windSpeedIn100Type = ZYWindSpeedIn100TypeMiddle;
                    break;
            }
            dict = @{@"windSpeedIn100":[NSNumber numberWithUnsignedInteger:windSpeedIn100Type],@"windPannelModel":[NSNumber numberWithUnsignedInteger:ZYVSModeTypManual]};
            //设置http 风速
            self.quickSetupViewModel.mac = _currentDevice.mac;
            [self.quickSetupViewModel setModeValueWithDeviceType:_currentDevice.serverDeviceType andModel:ZYVSModeTypManual andParams:[NSString stringWithFormat:@"%ld",(long)type]];
        }else{
            dict = @{@"windSpeed":[NSNumber numberWithUnsignedInteger:type],@"windPannelModel":[NSNumber numberWithUnsignedInteger:ZYVSModeTypManual]};
            //设置http 风速
            self.quickSetupViewModel.mac = _currentDevice.mac;
            [self.quickSetupViewModel setModeValueWithDeviceType:_currentDevice.serverDeviceType andModel:ZYVSModeTypManual andParams:[NSString stringWithFormat:@"%ld",(long)type]];
        }
    }else{
        dict = @{@"windSpeed":[NSNumber numberWithUnsignedInteger:type]};
    }
    [ZYSocketMessageUtils setDeviceWithMac:device.mac andParams:dict];
    _currentDevice.windSpeedType = type;
}

#pragma mark -ZYWorkModeSelectViewDelegate

-(void)workModeSelectView:(ZYWorkModeSelectView *)workModeSelectView setModeType:(NSUInteger)modeType{
    if(_currentDevice.isTest){
        return;
    }
    NSDictionary *dict = @{@"workModel":[NSNumber numberWithUnsignedInteger:modeType]};
    [ZYSocketMessageUtils setDeviceWithMac:_currentDevice.mac andParams:dict];
}

#pragma mark -Event

/**
 弹出或隐藏工作模式选择
 */
-(void)showAndHiddenWorkModeSelectView{
    [_workModeSelectView showOrHidden];
}


/**
 显示右边菜单
 @param button 按钮
 */
-(void)showRightMenu:(UIButton *)button{
    _isShowRightMenu = !_isShowRightMenu;
    if(_isShowRightMenu){
        [KxMenu setTintColor:[UIColor whiteColor]];
        [KxMenu setTitleFont:[UIFont systemFontOfSize:14]];
        //    CGRect rect =  CGRectMake(0, 0, 0, 0);
        NSArray *menuArray;
        if(_deviceType == ZYDeviceTypeAirConditioning){
            menuArray = _rightACMenuItemArray;
        }else if(_deviceType == ZYDeviceTypeRadiantFloorHeating){
            menuArray = _rightRFHMenuItemArray;
        }else{
            menuArray = _rightVSMenuItemArray;
        }
        [KxMenu showMenuInView:self.view fromRect:[self.navigationController.view convertRect:button.frame fromView:button.superview] menuItems:menuArray withOptions:[self setupMenuConfig]];
        //        [KxMenu showMenuInView:self.view
        //                      fromRect:[self.navigationController.view convertRect:button.frame fromView:button.superview]
        //                     menuItems:menuArray];
    }else{
        [KxMenu dismissMenu];
    }
}


/**
 配置菜单参数
 
 @return OptionalConfiguration
 */
-(OptionalConfiguration)setupMenuConfig{
    Color textColor;
    textColor.R = 102/255.0;
    textColor.G = 102/255.0;
    textColor.B = 102/255.0;
    Color menuBackgroundColor;
    menuBackgroundColor.R = 1;
    menuBackgroundColor.G = 1;
    menuBackgroundColor.B = 1;
    OptionalConfiguration config;
    config.arrowSize = 0;//指示箭头大小
    config.marginXSpacing = 5;  //MenuItem左右边距
    config.marginYSpacing = 8;  //MenuItem上下边距
    config.intervalSpacing = 10;//MenuItemImage与MenuItemTitle的间距
    config.menuCornerRadius = 5;//菜单圆角半径
    config.maskToBackground = NO;//是否添加覆盖在原View上的半透明遮罩
    config.hasSeperatorLine = NO;
    config.textColor = textColor; //menuItem字体颜色
    config.menuBackgroundColor = menuBackgroundColor;
    config.hasSeperatorLine = NO;
    return config;
}

/**
 温控策略
 */
-(void)gotoTemperatureControlStrategy{
    _isShowRightMenu = NO;
    if(_currentDevice.isTest){
        [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SELECT_DEVICE_PROMPT]];
        return;
    }
    ZYDevicePolicyVC *vc = [[ZYDevicePolicyVC alloc] init];
    vc.device = _currentDevice;
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 快捷设置
 */
-(void)gotoQuickSetup{
    _isShowRightMenu = NO;
    if(_currentDevice.isTest){
        [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SELECT_DEVICE_PROMPT]];
        return;
    }
    if(_deviceType == ZYDeviceTypeVentilationSystem){
        ZYVSQuickSetupVC *vc = [[ZYVSQuickSetupVC alloc] init];
        vc.device = _currentDevice;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        ZYQuickSetupVC *vc = [[ZYQuickSetupVC alloc] init];
        vc.device = _currentDevice;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

/**
 工作模式
 */
-(void)selectWorkMode{
    _isShowRightMenu = NO;
    if(_currentDevice.isTest){
        [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SELECT_DEVICE_PROMPT]];
        return;
    }
    [_workModeSelectView showOrHidden];
}


/**
 设备编辑
 */
-(void)gotoEquipmentEditing{
    _isShowRightMenu = NO;
    if(_currentDevice.isTest){
        [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SELECT_DEVICE_PROMPT]];
        return;
    }
    ZYDeviceModifyVC *vc = [[ZYDeviceModifyVC alloc] init];
    vc.device = _currentDevice;
    vc.mac = _currentDevice.mac;
    vc.isModify = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


/**
 历史数据
 */
-(void)gotoHistoricalData{
    _isShowRightMenu = NO;
    if(_currentDevice.isTest){
        [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SELECT_DEVICE_PROMPT]];
        return;
    }
    ZYHistoricalDataVC *vc = [[ZYHistoricalDataVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

/**
 删除设备
 */
-(void)deleteDevice{
    _isShowRightMenu = NO;
    if(_currentDevice.isTest){
        [[ToastHelper sharedToastHelper] toastError:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_SELECT_DEVICE_PROMPT]];
        return;
    }
    ZYChangeLanguage *language = [ZYChangeLanguage sharedZYChangeLanguage];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:[language getStringByKey:LC_DELETE_DEVICE_HINT] message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    @weakify(self)
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_ALERT_CONTER_BTN_CONFIRM] style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        @strongify(self);
        self.deviceViewModel.mac = _currentDevice.mac;
        [self.deviceViewModel.deleteCommand execute:nil];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:[language getStringByKey:LC_ALERT_CONTER_BTN_CANCEL] style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        return;
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - Getter

-(ZYDeviceViewModel *)deviceViewModel{
    if(!_deviceViewModel){
        _deviceViewModel = [[ZYDeviceViewModel alloc] init];
    }
    return _deviceViewModel;
}

-(ZYQuickSetupViewModel *)quickSetupViewModel{
    if(!_quickSetupViewModel){
        _quickSetupViewModel = [[ZYQuickSetupViewModel alloc] init];
    }
    return _quickSetupViewModel;
}

#pragma mark - socket

-(void)getDeviceData{
    device_communicate *message = [[device_communicate alloc] init];
    RHSocketPacketRequest *req = [[RHSocketPacketRequest alloc] init];
    message.module = 100;
    message.cmd = 1;
    message.sid = [ZYConfig loginToken];
    message.userId = [ZYConfig userId];
    message.macAddress = _currentDevice.mac;
    //    NSSet *data = [NSSet setWithArray:@[@"powerStatus",@"lockStatus",@"pannelModel"
    //                                        ,@"loadStatus",@"roomTemperatureC2",@"environmentAlarm1"
    //                                        ,@"deviceAlarm1",@"controlFlag",@"workModel",@"windSpeed",@"windPannelModel"]];
    message.jsonStr = @"";
    NSLog(@"json:%@",message.jsonStr);
    req.object = [message data];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSocketPacketRequest object:req];
}

-(void)receiveMsgData:(device_communicate *)data{
    if(!NULLString(data.jsonStr)){
        NSData *jsonData = [data.jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: jsonData options:NSJSONReadingAllowFragments error:nil];
        NSString *code = [dict objectForKey:@"code"];
        NSLog(@"module:%d",data.module);
        NSLog(@"cmd:%d",data.cmd);
        if([code integerValue] == 200){
            if(![[dict objectForKey:@"result"] isKindOfClass:[NSDictionary class]]){
                return;
            }
            ZYDevice *device = [ZYDevice modelWithJSON:[dict objectForKey:@"result"]];
            NSDictionary *result = [dict objectForKey:@"result"];
            NSDictionary *roomTemperatureC2 = [result objectForKey:@"roomTemperatureC2"];
            NSDictionary *setTemperatureC2 = [result objectForKey:@"setTemperatureC2"];
            if(roomTemperatureC2){
                _currentDevice.isConnect = YES;
                _currentDevice.isLock = device.isLock;
                _currentDevice.isOpen = device.isOpen;
                _currentDevice.curveType = device.curveType;
                _currentDevice.roomTemperature = device.roomTemperature;
                _currentDevice.workModeType = device.workModeType;
                _currentDevice.vsModeType = device.vsModeType;
                _currentDevice.windSpeedType = device.windSpeedType;
                _currentDevice.pmExponent = device.pmExponent;
                _currentDevice.outPmExponent = device.outPmExponent;
                _currentDevice.humidity = device.humidity;
                _currentDevice.outHumidity = device.outHumidity;
                _currentDevice.outTemperature = device.outTemperature;
                _currentDevice.formaldehyde = device.formaldehyde;
                _currentDevice.tvoc = device.tvoc;
                _currentDevice.carbonDioxide = device.carbonDioxide;
                _currentDevice.roomTemperature = [NSString stringWithFormat:@"%@",[roomTemperatureC2 objectForKey:@"value"]];
                _currentDevice.windSpeedIn100 = device.windSpeedIn100;
                if([[result allKeys] containsObject:@"windSpeedIn100"]){
                    _currentDevice.isNewVS = YES;
                }else{
                    _currentDevice.isNewVS = NO;
                }
                
                //更新视图
                CGFloat temperature = [[setTemperatureC2 objectForKey:@"value"] doubleValue];
                _currentDevice.temperature = [NSString stringWithFormat:@"%.0f",roundf(temperature)];
                _workModeSelectView.workModeType = _currentDevice.workModeType;
                _deviceItemView.device = _currentDevice;
                _deviceSwitchView.device = _currentDevice;
                self.quickSetupViewModel.mac = _currentDevice.mac;
                [self.quickSetupViewModel.modeValueCommand execute:[NSNumber numberWithUnsignedInteger:_currentDevice.serverDeviceType]];//获取风速
            }
        }
    }
}

-(void)connectSocketSuccess:(NSNotification *)notif{
    [self getDeviceData];//获取设备信息
}


-(ZYCurveViewModel *)viewModel{
    if(!_viewModel){
        _viewModel = [[ZYCurveViewModel alloc] init];
        _viewModel.macAddress = _currentDevice.mac;
    }
    return _viewModel;
}


@end
